<template>
  <view class="page-container">
    <HeaderBar
        title="详情"
        navBarBgc="linear-gradient(180deg, rgba(186,209,194,1) 0%, rgba(207,223,212,1) 33%, rgba(230,238,233,1) 100%);"
    ></HeaderBar>

    <view class="product-name">
      {{productName}}
    </view>

    <!-- Tab -->
    <view class="tabs-container">
      <view
          v-for="(tabItem, tabIndex) in tabList"
          :key="tabIndex"
          class="tab"
          @click="scrollToSection(tabIndex)"
      >
        <img v-show="tabIndex === tabActiveIndex" class="img" src="http://img.jowong.com/aba/2025-03-26/未命名 -1_11_1742951965378.png" />
        <text :class="['tab-title', tabIndex === tabActiveIndex ? 'active-tab-title' : '']">{{ tabItem }}</text>
        <img class="circle-img" src="http://img.jowong.com/aba/2025-03-26/图层 538_1742952400702.png">
      </view>
    </view>

    <!-- 滚动内容 -->
    <scroll-view scroll-y class="content" @scroll="onScroll" :scroll-into-view="scrollTarget">
      <view id="detail" class="detail-container">
        <view class="second-title-container flex items-center">
          <i class="iconfont icon-menpiao"></i>
          <text class="ml10">详情</text>
          <view class="bottom-border"></view>
        </view>
		<view style="padding: 20rp;">
			<rich-text :nodes="productInfoObj.detail" @tap="handleRichText"></rich-text>
		</view>
        
      </view>
      <view id="reservation" class="reservation-container detail-container">
        <view class="second-title-container flex items-center" style="margin-left: 0">
          <i class="iconfont icon-menpiao"></i>
          <text class="ml10">预约选择</text>
          <view class="bottom-border" style="width: 160rpx"></view>
        </view>
        <view class="fs15 pb30 fwb">使用日期</view>
        <ChooseDate
            :defaultDate="defaultDate"
            :startDate="startDate"
            @changeDate="changeDate"
        ></ChooseDate>
        <view class="fs15 pb30 pt30 fwb">使用时间段</view>
        <view class="time-list-container flex-warp">
          <view
              v-for="(item, index) in timeSlotList"
              :key="index"
              class="time-item"
              :class="['time-item',timeId === item.id ? 'choose-active' : '',isTimePassed(item) ? 'disabled' : '']"
              @click="!isTimePassed(item) && changeTimeSlot(item)"
          >
            {{item.startTime}} - {{item.endTime}}
          </view>
        </view>
        <view class="fs15 pb30 pt30 fwb" v-if="crowdList.length">使用人群</view>
        <view class="crowed-list-container flex-warp">
          <view
              v-for="(item,index) in crowdList"
              :key="index"
              :class="['crowed-item',index === crowdActive ? 'choose-active' : '']"
              @click="changeCrowd(item,index)"
          >
            {{item.skuName}}
          </view>
        </view>
      </view>
      <view id="sale" class="sale-instructions-container detail-container">
        <view class="second-title-container flex items-center" style="margin-left: 0">
          <i class="iconfont icon-menpiao"></i>
          <text class="ml10">购买须知</text>
          <view class="bottom-border" style="width: 160rpx"></view>
        </view>
        <rich-text :nodes="productInfoObj.bookingNote"></rich-text>
      </view>
    </scroll-view>
    <view class="btn-bottom-container">
      <view class="top-container flex ">
        <view class="price">￥ {{ticketPrice}}</view>
        <view class="right-container">
<!--          <view class="price-detail-tip" @click="showDetail = true">
            <text>明细</text>
            <wd-icon name="arrow-down" size="22px"></wd-icon>
          </view>-->
          <view class="btn" @click="handNavReservation">去预定</view>
        </view>
      </view>
      <view class="safe-content" :style="{height: safeInsert + 'px'}"></view>
    </view>
    <wd-popup v-model="showNotice" closable  custom-style="border-radius:12rpx;" >
      <view class="notice-container">
        <view class="fw800">提示</view>
        <text class="custom-txt">{{productInfoObj.warn}}</text>
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
  import { ref } from "vue";
  import {onLoad} from "@dcloudio/uni-app";
  import ChooseDate from "@/components/ChooseDate/index.vue";
  import HeaderBar from "@/components/HeaderBar/index.vue";
  import { useMixin } from "@/hook/useMixin";
  import dayjs from "dayjs";
  import {crowdTypeList, productDetail, timeSlotStock} from "@/api/ticket";

  const { pageBack,transferWeekDay } = useMixin();

  const tabList = ref(["详情", "预约选择", "购买须知"]);
  const timeActive = ref(0);
  const safeInsert = ref(0);
  const startDate = ref( dayjs().format("YYYY-MM-DD"));
  const defaultDate = ref( dayjs().format("YYYY-MM-DD"));
  const minDate = ref("");
  const maxDate = ref("");
  const providerId = ref("");
  const productName = ref("");
  const productId = ref(null);
  const crowdList = ref([]);
  const ticketPrice = ref(0);
  const ticketPriceId = ref(null);
  // 人群种类 ID
  const skuId = ref(null);
  const crowdActive = ref(0);
  const productInfoObj = ref({});
  const showNotice = ref(false);
  const timeSlotList = ref([]);
  const timeId = ref("");
  const stockId = ref("");
  const timeSlot = ref("");


  const sections = ref(["detail", "reservation", "sale"]);
  const tabActiveIndex = ref(0);
  const scrollTarget = ref(""); // scroll-into-view 目标

  const handleRichText = (event) => {
    console.log(event,'event');
    console.log(event.target,'event.target');
  }
  // 点击 tab 滚动到对应内容
  const scrollToSection = (index) => {
    scrollTarget.value = sections.value[index]; // 让 scroll-view 滚动
    tabActiveIndex.value = index;
  };

  // 监听滚动，自动高亮 tab
  const onScroll = (event) => {
    uni.createSelectorQuery()
        .selectAll(".detail-container, .reservation-container, .sale-instructions-container")
        .boundingClientRect((res) => {
          res.forEach((item, index) => {
            if (item.top <= 300) {
              tabActiveIndex.value = index;
            }
          });
        })
        .exec();
  };
  
  const isTimePassed = (timeStr) => {
    if(startDate.value != dayjs().format("YYYY-MM-DD")){
		return false
    } else {
	  console.log(timeStr,defaultDate.value,startDate.value);
  	const [hours, minutes] = timeStr.endTime.split(":").map(Number);
  	const now = new Date();
  	const compareTime = new Date();
  	compareTime.setHours(hours, minutes, 0, 0);
  	return now > compareTime; 
    }
  };
  const handNavReservation = () => {
    if(crowdList.value && crowdList.value.length > 0) {
      let crowdProductList = JSON.parse(JSON.stringify(crowdList.value));
      let choiceCrowdProductItem = crowdProductList.splice(crowdActive.value,1);
      choiceCrowdProductItem[0].number = 1;
      crowdProductList.forEach(item => item.number = 0);
      crowdProductList.unshift(...choiceCrowdProductItem);
      uni.setStorageSync("reservationProductList",crowdProductList);
    }
    let weekDay = transferWeekDay(startDate.value);
    uni.navigateTo({
      url:`/ticketSubPack/pages/ticketOrderReservation/index?weekDay=${weekDay}&timeSlot=${timeSlot.value}&startDate=${startDate.value}&providerId=${providerId.value}&stockId=${stockId.value}&subStockId=${timeId.value}&productName=${productName.value}`
    });
  };
  const changeDate = (event) => {
    let {date} = event;
    startDate.value = date;
	timeId.value = ''
    queryCrowdTypeList();
    queryTimeSlotStock();
  };
  const queryCrowdTypeList = async () => {
    // console.log({productId:productId.value,playDate:startDate.value},'{productId:productId.value,playDate:startDate.value')
    await crowdTypeList({productId:productId.value,playDate:startDate.value}).then(res => {
      console.log(res,'crowdList')
      let {result} = res;
      if(result && result.length > 0) {
        let {price,priceId,skuId:_crowd} = result[0];
        ticketPrice.value = price;
        skuId.value = _crowd;
        ticketPriceId.value = priceId;
        crowdList.value = result;
      }
      console.log(crowdList,'crowdList');
    });
  };
  const queryProductDetail = async () => {
    await productDetail({
      productId:Number(productId.value),merchantId:Number(providerId.value),playDate:startDate.value
    }).then(res => {
      let {result} = res;
      let {maxPreBook,minPreBook} = result;
      console.log(maxPreBook,'maxPreBook');
      console.log(minPreBook,'minPreBook');
      console.log(dayjs(new Date()).add(minPreBook,'days').format("YYYY-MM-DD"),'minDate');
      productInfoObj.value = result;
      if(res.foreWarn) {
        showNotice.value = true;
      }
      console.log(res,'queryProductDetail')
    });
  };
  const queryTimeSlotStock = async () => {
    await timeSlotStock({
      productId:Number(productId.value),
      merchantId:Number(providerId.value),
      playDate:startDate.value
    }).then(res => {
      console.log(res,'queryTimeSlotStock');
      let {merchant:{subStocks,id}} = res.result;
      stockId.value = id;
      if(subStocks && subStocks.length) {
        timeSlotList.value = subStocks;
        let {id,startTime,endTime} = subStocks[0];
        // timeId.value = id;
        console.log(subStocks[0],'subStocks[0]');
        timeSlot.value = startTime + "-" + endTime;
      }
    });
  };
  const changeCrowd = (item,index) => {
    let {skuId:_crowd,priceId,price} = item;
    ticketPrice.value = price;
    skuId.value = _crowd;
    ticketPriceId.value = priceId;
    crowdActive.value = index;
  };
  const changeTimeSlot = (item,index) => {
    let {id,stockId:_stockId} = item;
    timeId.value = id;
    stockId.value = _stockId;
  };

  onLoad((options) => {
    let {startDate:_startDate,productId:_productId,productName:_productName,providerId:_providerId} = options;
    startDate.value = _startDate;
    defaultDate.value = _startDate;
    providerId.value = _providerId;
    productId.value = _productId;
    productName.value = _productName;
    safeInsert.value = uni.getSystemInfoSync().safeAreaInsets.bottom;
	scrollToSection(options.type)
    queryCrowdTypeList();
    queryProductDetail();
    queryTimeSlotStock();
  });

</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

/* 顶部标题 */
.nav-title {
  font-size: 30rpx;
  font-weight: normal;
  color: #2D2D2D;
}

/* 产品名称 */
.product-name {
  font-size: 42rpx;
  padding: 50rpx 27rpx;
  font-weight: bold;
  background: linear-gradient(180deg, rgba(231,239,234,1) 0%, rgba(239,244,241,1) 33%, rgba(255,255,255,1) 100%);
}

/* Tab 样式 */
.tabs-container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 16rpx 19.5rpx;
  background: #1b9c61;

  .tab {
    position: relative;
    width: 236rpx;
    height: 82.5rpx;
    text-align: center;

    .img {
      position: absolute;
      left: 0;
      bottom: -32rpx;
      width: 100%;
      height: 100%;
    }
    .tab-title {
      position: absolute;
      top:34rpx;
      left: 0;
      width: 236rpx;
      text-align: center;
      color: #FFFFFF;
    }
    .active-tab-title {
      color: #AA5413;
      font-weight: bold;
    }
    .circle-img {
      position: absolute;
      width: 70rpx;
      height: 16rpx;
      bottom: -10rpx;
      left: 50%;
      margin-left: -35rpx;
    }
  }
}

/* 滚动区域 */
.content {
  flex: 1;
  overflow-y: auto;
  margin-top: 10rpx;
}

/* 各个 section */
.detail-container {
  padding: 20rpx 27rpx;
  min-height: 100rpx;
  .second-title-container {
    margin: 50rpx 0 30rpx 0rpx;
    position: relative;
    .icon-menpiao {
      color: #1b9c61;
      font-size: 30rpx;
    }
    text {
      font-size: 29rpx;
      font-weight: bold;
    }
    .bottom-border {
      position: absolute;
      left: 0;
      bottom: -6rpx;
      height: 7rpx;
      width: 100rpx;
      border-radius: 20rpx;
      background: linear-gradient(90deg, rgba(27,156,97,1) 0%, rgba(128,200,167,1) 50%, rgba(243,250,247,0) 100%);
    }
  }
}
.reservation-container {
  .time-list-container {
    .time-item {
      font-size: 20rpx;
      padding: 10rpx 18rpx;
      border-radius: 10.5rpx;
      margin-right: 10rpx;
      background: #EEF0DF;
    }
  }
.disabled {
  color: #999 !important;
  background: #ddd !important;
  pointer-events: none; // 禁止点击
}
  .crowed-list-container {
    .crowed-item {
      padding: 22rpx;
      font-size: 25rpx;
      border-radius: 10rpx;
      color: #181818;
      margin-right: 20rpx;
      background: #EEF0DF;
      margin-bottom: 20rpx;
    }
  }
}
.sale-instructions-container {
  min-height: 1200rpx;
  padding: 0 27rpx 400rpx 27rpx;
}
.btn-bottom-container {
  position: fixed;
  width: 100%;
  bottom: 0;
  left: 0;
  background: #fdffeb;
  .top-container {
    justify-content: space-between;
    align-items: center;
    padding: 32rpx 20rpx 0 59rpx;
    .price {
      font-size: 42rpx;
      font-weight: bold;
      color: #AA5413;
    }
    .right-container {
      display: flex;
      align-items: center;
      .price-detail-tip {
        display: flex;
        align-items: center;
        padding-right: 11rpx;
        text {
          font-size: 30rpx;
        }
      }
      .btn {
        border-radius: 10.5rpx;
        font-weight: bold;
        padding: 25rpx 32rpx;
        color: #FDFFEB;
        background: #AA5413;
      }
    }
  }
}
.choose-active {
  color: #FFFFFF !important;
  background: #1b9c61 !important;
}
.notice-container {
  width: 600rpx;
  padding: 30rpx;
  text-align: center;
}
</style>
